from flask import jsonify, Blueprint, request
from flask_restful import Api, Resource, reqparse

from models.model import *

good_bp = Blueprint('good_bp', __name__)
api = Api(good_bp)


class GoodView(Resource):
    def get(self):
        req = reqparse.RequestParser()
        req.add_argument('name')
        req.add_argument('code')
        req.add_argument('supplierId')
        req.add_argument('page', type=int)
        req.add_argument('per_page', type=int)
        args = req.parse_args()
        good_name = args['name']
        good_code = args['code']
        vendor_id = args['supplierId']
        page = args.get("page", 1)
        limit = args.get("per_page", 5)

        sql = db.session.query(Good)
        if good_name:
            sql = sql.filter(Good.name.like(f"%{good_name}%"))
        if good_code:
            sql = sql.filter(Good.code.like(f"%{good_code}%"))
        if vendor_id:
            sql = sql.filter(Good.supplierId.like(f"%{vendor_id}%"))

        good_info = sql.paginate(page, limit)
        good_list = []

        for good_one in good_info.items:
            a = {
                "id": good_one.id,
                "name": good_one.name,
                "code": good_one.code,
                "pec": good_one.pec,
                "retailPrice": good_one.retailPrice,
                "purchasePrice": good_one.purchasePrice,
                "storageNum": good_one.storageNum,
                "supplierId": good_one.supplierId,
                "supplierName": good_one.supplierName,
            }
            good_list.append(a)
        return jsonify({
            'code': 200,
            'msg': '获取成功',
            'good_list': good_list
        })

    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('supplierId', required=True)
        req.add_argument("name", required=True)
        req.add_argument("code", required=True)
        req.add_argument("pec", required=True)
        req.add_argument("retailPrice", required=True)
        req.add_argument("purchasePrice", required=True)
        req.add_argument("storageNum", required=True)
        args = req.parse_args()
        vendor = db.session.query(Vendor.name).filter(Vendor.id==args["supplierId"]).one()
        try:
            good = Good(**args, supplierName=vendor.name)
            db.session.add(good)
            db.session.commit()
        except:
            return jsonify({
                'code': 400,
                'msg': '添加失败'
            })
        return jsonify({
            'code': 200,
            'msg': '添加成功'
        })


class GoodOneView(Resource):
    def get(self, id):
        good_one = db.session.query(Good).filter(Good.id == id).first()

        if not good_one:
            return jsonify({
                'code': 400,
                'msg': '商品不存在'
            })
        good_list = {
            "id": good_one.id,
            "name": good_one.name,
            "code": good_one.code,
            "pec": good_one.pec,
            "retailPrice": good_one.retailPrice,
            "purchasePrice": good_one.purchasePrice,
            "storageNum": good_one.storageNum,
            "supplierId": good_one.supplierId,
            "supplierName": good_one.supplierName,
        }
        return jsonify({
            'code': 200,
            'msg': "获取成功",
            'vendor_list': good_list
        })

    def put(self, id):
        args = request.form
        good_one = Good.query.filter(Good.id == id).first()
        if not good_one:
            return jsonify({
                'code': 400,
                'msg': '商品不存在'
            })
        try:
            Good.query.filter(Good.id == id).update(args)
            db.session.commit()
            return jsonify({
                'code': 200,
                'msg': '更新成功'
            })
        except Exception as e:
            print(e)
            return jsonify({
                'code': 400,
                'msg': f'更新失败 {e}'
            })

    def delete(self, id):
        good_one = Good.query.filter(Good.id == id).first()
        if not good_one:
            return jsonify({
                'code': 400,
                'msg': '商品不存在'
            })
        Good.query.filter(Good.id == id).delete()
        db.session.commit()
        return jsonify({
            'code': 200,
            'msg': '删除成功'
        })


api.add_resource(GoodView, '/v2/goods')
api.add_resource(GoodOneView, '/v2/goods/<int:id>')
